package com.ruoyi.slope.gateway.service.impl;

import com.ruoyi.slope.gateway.domain.SlopeGatewayInfo;
import com.ruoyi.slope.gateway.service.ISlopeGatewaySoundAlarm;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class SlopeGatewaySoundAlarmImpl implements ISlopeGatewaySoundAlarm {

    @Autowired
    private RestTemplate restTemplate;
    @Autowired
    private SlopeGatewayInfoServiceImpl slopeGatewayInfoServiceImpl;

    public int alarm(SlopeGatewayInfo slopeGatewayInfo) {
        if (slopeGatewayInfo == null) {
            return 0;
        }
        String tokenUrl = "http://www.iot-monitor.cn/chcnavAuthThings/iot/login";
        String alarmUrl = "http://www.iot-monitor.cn/iot/bro_api/device/command/send";

        // Step 1: 获取 access_token
        HttpHeaders tokenHeaders = new HttpHeaders();
        tokenHeaders.setContentType(MediaType.APPLICATION_JSON);
        tokenHeaders.set("clientId", "QGO6P3pjR7yd7mUpdLVUTQ");
        tokenHeaders.set("clientkey", "6rZPjYmMRw6OKi-P6TrWOw");

        Map<String, String> tokenBody = new HashMap<>();
        tokenBody.put("username", "东北林业大学");
        tokenBody.put("password", "enAQ6hsVAxmmp0oSWiV16w==");

        HttpEntity<Map<String, String>> tokenRequest = new HttpEntity<>(tokenBody, tokenHeaders);

        String accessToken;
        try {
            ResponseEntity<Map> response = restTemplate.postForEntity(tokenUrl, tokenRequest, Map.class);
            Map<String, Object> respBody = response.getBody();
            if (response.getStatusCodeValue() == 200 && (Integer) respBody.get("code") == 200) {
                Map<String, Object> data = (Map<String, Object>) respBody.get("data");
                accessToken = (String) data.get("access_token");
            } else {
                System.err.println("获取 access_token 失败：" + respBody);
                return -1;
            }
        } catch (Exception e) {
            e.printStackTrace();
            return -2;
        }

        // Step 2: 报警 deviceA 和 deviceB
        List<String> deviceList = new ArrayList<>();
        if (slopeGatewayInfo.getDeviceA() != null && !slopeGatewayInfo.getDeviceA().isEmpty()) {
            deviceList.add(slopeGatewayInfo.getDeviceA());
        }
        if (slopeGatewayInfo.getDeviceB() != null && !slopeGatewayInfo.getDeviceB().isEmpty()) {
            deviceList.add(slopeGatewayInfo.getDeviceB());
        }

        for (String deviceSn : deviceList) {
            HttpHeaders alarmHeaders = new HttpHeaders();
            alarmHeaders.setContentType(MediaType.APPLICATION_JSON);
            alarmHeaders.set("bro_token", accessToken);

            Map<String, Object> alarmBody = new HashMap<>();
            alarmBody.put("device_sn", deviceSn);
            alarmBody.put("commandId", "30");

            List<Map<String, Object>> commandArgs = new ArrayList<>();
            commandArgs.add(Map.of("id", "numVal", "value", 3));
            commandArgs.add(Map.of("id", "sizeVal", "value", 10));
            commandArgs.add(Map.of("id", "contentVal", "value", "前方落石，请谨慎驾驶"));
            alarmBody.put("commandArgs", commandArgs);

            HttpEntity<Map<String, Object>> alarmRequest = new HttpEntity<>(alarmBody, alarmHeaders);
            try {
                ResponseEntity<Map> alarmResp = restTemplate.exchange(
                        alarmUrl,
                        HttpMethod.PUT,
                        alarmRequest,
                        Map.class
                );
                Map<String, Object> alarmResult = alarmResp.getBody();
                if (alarmResp.getStatusCodeValue() != 200 || (Integer) alarmResult.get("code") != 200) {
                    System.err.println("报警失败：" + alarmResult);
                    return -3;
                }
                System.out.println(alarmResp.getStatusCodeValue());
            } catch (Exception e) {
                e.printStackTrace();
                return -4;
            }
        }

        return 1; // 成功
    }
}
